from sqlalchemy.orm import Session
from sqlalchemy import func
from models.models import BatchProcesses, FileUploadsBatch

class FileDao:
    @staticmethod
    def create_batch(db: Session, batch_id: str, sort_prompt: str, user_id: int):
        """
        创建文件上传批次
        
        Args:
            db (Session): 数据库会话
            batch_id (str): 批次ID
            sort_prompt (str): 排序提示词
            user_id (int): 用户ID
            
        Returns:
            FileUploadsBatch: 创建的批次记录
        """
        batch = FileUploadsBatch(
            batch_id=batch_id,
            user_id=user_id,
            sort_prompt=sort_prompt,
            status=0
        )
        db.add(batch)
        db.commit()
        return batch

    @staticmethod
    def create_process(db: Session, batch_id: str, file_name: str, file_url: str, file_type: int, file_original_url: str):
        """
        创建文件处理记录
        
        Args:
            db (Session): 数据库会话
            batch_id (str): 批次ID
            file_name (str): 文件名
            file_url (str): 处理后的文件URL
            file_type (int): 文件类型
            file_original_url (str): 原始文件URL
            
        Returns:
            BatchProcesses: 创建的处理记录
        """
        process = BatchProcesses(
            batch_id=batch_id,
            file_name=file_name,
            file_url=file_url,
            file_original_url=file_original_url,
            status=0,
            type=file_type
        )
        db.add(process)
        db.commit()
        return process

    @staticmethod
    def get_user_batches_count(db: Session, user_id: int) -> int:
        """
        获取用户的批次总数
        
        Args:
            db (Session): 数据库会话
            user_id (int): 用户ID
            
        Returns:
            int: 批次总数
        """
        return db.query(FileUploadsBatch)\
            .filter(FileUploadsBatch.user_id == user_id)\
            .count()

    @staticmethod
    def get_user_batches(db: Session, user_id: int, page_num: int = 1, page_size: int = 10):
        """
        获取用户的批次列表
        
        Args:
            db (Session): 数据库会话
            user_id (int): 用户ID
            page_num (int, optional): 当前页码，从1开始. Defaults to 1
            page_size (int, optional): 每页显示的记录数. Defaults to 10
            
        Returns:
            dict: 包含批次列表和分页信息的字典
                - items (list): 批次列表
                - total (int): 总记录数
                - page (int): 当前页码
                - size (int): 每页大小
                - pages (int): 总页数
        """
        # 先获取总记录数
        total_query = db.query(func.count(FileUploadsBatch.id))\
            .filter(FileUploadsBatch.user_id == user_id)
        total = total_query.scalar()
        
        # 计算总页数
        pages = (total + page_size - 1) // page_size
        
        # 计算偏移量
        offset = (page_num - 1) * page_size
        
        # 直接查询当前页数据
        batches_query = db.query(FileUploadsBatch)\
            .filter(FileUploadsBatch.user_id == user_id)\
            .order_by(FileUploadsBatch.created_at.desc())
            
        # 添加分页
        batches_query = batches_query.limit(int(page_size)).offset(int(offset))
        
        batches = batches_query.all()
            
        return {
            "items": batches,
            "total": total,
            "page": page_num,
            "size": page_size,
            "pages": pages
        }

    @staticmethod
    def get_batch_processes(db: Session, batch_id: str):
        """
        获取批次的所有处理记录
        
        Args:
            db (Session): 数据库会话
            batch_id (str): 批次ID
            
        Returns:
            list[BatchProcesses]: 处理记录列表
        """
        return db.query(BatchProcesses)\
            .filter(BatchProcesses.batch_id == batch_id)\
            .order_by(BatchProcesses.created_at.asc())\
            .all()

    @staticmethod
    def get_batch_by_id(db: Session, batch_id: str) -> FileUploadsBatch:
        """
        根据ID获取批次信息
        
        Args:
            db (Session): 数据库会话
            batch_id (str): 批次ID
            
        Returns:
            FileUploadsBatch: 批次信息，如果不存在返回None
        """
        return db.query(FileUploadsBatch)\
            .filter(FileUploadsBatch.batch_id == batch_id)\
            .first()

    @staticmethod
    def update_batch_status(db: Session, batch: FileUploadsBatch, new_status: int) -> FileUploadsBatch:
        """
        更新批次状态
        
        Args:
            db (Session): 数据库会话
            batch (FileUploadsBatch): 批次对象
            new_status (int): 新状态
            
        Returns:
            FileUploadsBatch: 更新后的批次对象
        """
        batch.status = new_status
        db.flush()
        return batch 

    @staticmethod
    def update_batch_processes_status(db: Session, batch_id: str, new_status: int):
        """
        更新批次下所有文件的状态
        
        Args:
            db (Session): 数据库会话
            batch_id (str): 批次ID
            new_status (int): 新状态
            
        Returns:
            int: 更新的记录数
        """
        result = db.query(BatchProcesses)\
            .filter(BatchProcesses.batch_id == batch_id)\
            .update({"status": new_status})
        db.flush()
        return result 
